﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using static simu485.Views.C485SrvCmd;

namespace simu485.Views
{
    public class C485CmdDef
    {
        public string cmd { get; set; } = "";       // 类似："0203"
        public string des { get; set; } = "";       // 类似："库设置温度设定"
        public string value { get; set; } = "";     // 类似："11 22 33 44"; 根据首字母，长度自动区分发送数据类型

        // public string type { get; set; } = "";     // 类似："byte"; byte/short/int/string/data; data是指大量数据
    }

    public class C485CmdDefTable
    {

        public List<C485CmdDef> cmd_list = new();
        private string file_name = @"c485_cmd_table.ini";

        public void Load()
        {
            // 加载485命令配置数据
            if (File.Exists(file_name))
            {
                string jsonString = File.ReadAllText(file_name);
                cmd_list = JsonSerializer.Deserialize<List<C485CmdDef>>(jsonString)!;
            }
            else
            {
                cmd_list.Clear(); // 做个例子
                C485CmdDef item = new();
                item.cmd = "0203";
                item.des = "库设置温度设定";
                item.value = "50";
                cmd_list.Add(item);
                item = new();
                item.cmd = "0204";
                item.des = "库设置温度取得";
                item.value = "00";
                cmd_list.Add(item);
                
                Save();
            }
        }

        public void Save()
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            };
            string jsonString = JsonSerializer.Serialize(cmd_list, options);
            File.WriteAllText(file_name, jsonString);
        }
    }
}
